<?php

namespace app\backstage\controller;

use app\backstage\model\Link;
use think\Controller;
use think\Db;
use think\facade\Request;

class Baidu extends Controller
{

    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['activeReport']],
    ];

    public function index()
    {
        return $this->fetch();
    }

    public function list_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $Baidu = \think\facade\App::model('Baidu', 'logic');
        $result = $Baidu->getList($params);

        return sucJson($result['list'], $result['count']);
    }

    public function add()
    {
        if( Request::isGet() ){
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags,trim');

        $verify_result = $this->validate($params, 'baidu.add');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $Baidu = \think\facade\App::model('Baidu','logic');
        while (true) {
            $mySign = $this->randStr();
            $info = $Baidu->getInfo(['mysign' => $mySign]);
            if (!$info) {
                break;
            }
        }
        $params['mysign'] = $mySign;
        $params['channel_id'] = request()->_user->id;
        $ManagerUser = \think\facade\App::model('Account');
        $m = $ManagerUser->getOne(['id' => $params['channel_id']], 'parent_id');
        $params['agent_id'] = $m['parent_id'];


        $r = $Baidu->addInfo($params);
        if ($r) {
            return ['code'=>100,'msg'=>'操作成功'];
        }
        return ['code'=>102,'msg'=>'操作失败'];
    }

    private function randStr($length = 8) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    public function delete()
    {
        $params = Request::get('','','strip_tags,trim');

        $verify_result = $this->validate($params, 'baidu.info');
        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }
        $Baidu = \think\facade\App::model('Baidu','logic');
        return $Baidu->editInfo(['id' => $params['id']], ['status' => 0]);
    }

    /**
     * 激活
     * @return mixed
     */
    public function debugger()
    {
        $id = input('id');
        if (!$id) {
            $this->error('参数异常');
        }
        $user = request()->_user;
        $monitor = getLinkMacroParameters(4, $user->id);
        $mysign = Db::table("quick_ad_account_baidu")->where("id", $id)->value('mysign');
        if (!$mysign){
            $this->error('数据异常');
        }
        $monitor = $monitor . "&mysign={$mysign}";
        $jhLink = config('ht_domain') . "/baidu/activeReport?mysign={$mysign}";
        $suffix = '&adtype=baidu&bd_vid=__BD_VID__&click_id=__CLICK_ID__&oaid=__OAID__';
        $this->assign('suffix', $suffix);
        $this->assign('monitor', $monitor);
        $this->assign('jhLink', $jhLink);
        return $this->fetch();
    }



    //新百度账户回传激活
    //文档地址：https://dev2.baidu.com/content?sceneType=0&pageId=101213&nodeId=663&subhead=
    public function activeReport(){
        $mysign = input('mysign');
        $user = request()->_user;

        $where[] = ['mysign', '=', $mysign];
        $where[] = ['channel_id', '=', $user->id];
        $cinfo = Db::table('quick_ad_account_baidu')->where($where)->find();

        if(!$cinfo){
            $res = [
                'code'=>101,
                'msg'=>'激活失败，后台百度账号不存在'
            ];
            return json($res);
        }

        //查找最新过来的百度通知
        $adwhere[] = ['channel_id','=',$cinfo['channel_id']];
        $adwhere[] = ['adsign','=',$mysign];
        $last_adinfo = Db::table('quick_user_behavior_monitoring')->where($adwhere)->order('id desc')->find();

        if(!$last_adinfo){
            $res = [
                'code'=>102,
                'msg'=>'激活失败，无用户广告行为'
            ];
            return json($res);
        }

        $adinfo_str = $last_adinfo['link'];
        $adinfo = json_decode($adinfo_str,true);

        $callback_url = $adinfo['callback_url'] ?: '';
        if($callback_url == ''){
            $res = [
                'code'=>103,
                'msg'=>'激活失败，无callback_url'
            ];
            return json($res);
        }

        //新的激活类型
        //deeplink：应用调起
        //pay_to_read:付费阅读
        //enter_bookstore_read:进入书城阅读
        //add_to_desktop:添加到桌面
        //user_defined:客户自定义(这个要填写下载链接，暂时不用了)
        $apiUrl = str_replace("{{ATYPE}}","pay_to_read",$callback_url);
        $apiUrl = str_replace("{{AVALUE}}",0,$apiUrl);

        //新增 转化数据归因方式，用于辅助百度优化投放效果（必填字段）
        $apiUrl = $apiUrl.'&join_type=ip';
        //加应用起调的激活
        $apiUrl_deeplink = str_replace("pay_to_read","deeplink",$apiUrl);
        //进入书城阅读的激活
        $apiUrl_enter_read = str_replace("pay_to_read","enter_bookstore_read",$apiUrl);
        //添加到桌面的激活
        $apiUrl_add_desktop = str_replace("pay_to_read","add_to_desktop",$apiUrl);
        //客户自定义
        $apiUrl_user_defined = str_replace("pay_to_read","user_defined",$apiUrl);

        try {
            $tips = [];
            $actnum = 0;
            //付费阅读激活
            $result_str = file_get_contents($apiUrl);
            $result = json_decode($result_str, true);
            //dump($result);
            if($result['error_code'] == 0){
                $actnum++;
                $tips[] = 'active_pay_to_read:success';
            }else{
                $tips[] = 'active_pay_to_read:fail res:'.$result_str;
            }

            //应用调起激活
            $result_deeplink_str = file_get_contents($apiUrl_deeplink);
            $result_deeplink = json_decode($result_deeplink_str, true);
            if($result_deeplink['error_code'] == 0){
                $actnum++;
                $tips[] = 'active_feed_deeplink:success';
            }else{
                $tips[] = 'active_feed_deeplink:fail res:'.$result_deeplink_str;
            }

            //进入书城阅读
            $result_enter_read_str = file_get_contents($apiUrl_enter_read);
            $result_enter_read = json_decode($result_enter_read_str, true);
            if($result_enter_read['error_code'] == 0){
                $actnum++;
                $tips[] = 'active_enter_bookstore_read:success';
            }else{
                $tips[] = 'active_enter_bookstore_read:fail res:'.$result_enter_read_str;
            }

            //添加到桌面激活
            $result_add_desktop_str = file_get_contents($apiUrl_add_desktop);
            $result_add_desktop = json_decode($result_add_desktop_str, true);
            if($result_add_desktop['error_code'] == 0){
                $actnum++;
                $tips[] = 'active_add_to_desktop:success';
            }else{
                $tips[] = 'active_add_to_desktop:fail res:'.$result_add_desktop_str;
            }

            //客户自定义
            /*$result_user_defined_str = file_get_contents($apiUrl_user_defined);
            $result_user_defined = json_decode($result_user_defined_str, true);
            if($result_user_defined['error_code'] == 0){
                $actnum++;
                $tips[] = 'active_user_defined:success';
            }else{
                $tips[] = 'active_user_defined:fail res:'.$result_add_desktop_str;
            }*/

            $code = 0;
            //全部失败
            if($actnum == 0){
                $code = 104;
                $msg = $cinfo['accountname'].' 广告账户激活失败';
            }
            //全部成功
            else if($actnum == 4){
                $msg = $cinfo['accountname'].' 广告账户激活成功';
                //都成功了更新下激活状态
                $updata = ['isact'=>1];
                Db::table('quick_ad_account_baidu')->where(['id'=>$cinfo['id']])->update($updata);

            }
            //部分成功提示
            else{
                $code = 103;
                $msg = $cinfo['accountname'].' 广告账户部分类型激活成功';
            }

            $res = [
                'code'=>$code,
                'msg'=>$msg,
                'tips'=>$tips
            ];
            return json($res);

        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
}


